/*
  学习目标：数据缓存
*/

import React, { useEffect, useState } from 'react';
import Footer from './components/Footer';
import Header from './components/Header';
import Main from './components/Main';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  const [list, setList] = useState([]);
  const [type, setType] = useState('all');

  const showList = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });

  const handleDelById = (id) => {
    const newList = list.filter((item) => item.id !== id);
    setList(newList);
  };

  const handleUpdateById = (id) => {
    const newList = list.map((item) => ({
      ...item,
      isDone: item.id === id ? !item.isDone : item.isDone,
    }));

    setList(newList);
  };

  const handleAdd = (task) => {
    const newTask = { id: Date.now(), task, isDone: false };
    setList([newTask, ...list]);
  };

  const handleUpdateType = (type) => {
    setType(type);
  };
  // 2. 挂载后, 从缓存中取出数据, 作为初始值
  useEffect(() => {
    const newList = JSON.parse(localStorage.getItem('todo-list-80') || '[]');
    setList(newList);
  }, []);

  // 1. 监听list的变化, 每次变化, 立马把更新后只的存入缓存
  useEffect(() => {
    localStorage.setItem('todo-list-80', JSON.stringify(list));
  }, [list]);

  return (
    <section className="todoapp">
      <Header handleAdd={handleAdd} />
      <Main list={showList} handleDelById={handleDelById} handleUpdateById={handleUpdateById} />
      <Footer type={type} handleUpdateType={handleUpdateType} />
    </section>
  );
}
